<template>
  <j-modal :confirmLoading="confirmLoading" :title="title" :visible="visible" :width="1200" cancelText="关闭"
           switchFullscreen @cancel="handleCancel" @ok="handleOk">
    <template slot="footer">
      <a-button @click="handleCancel">取消</a-button>
      <a-button v-if="title=='审批'" :loading="confirmLoading" type="primary" @click="handleOk(4)">
        驳回
      </a-button>
      <a-button v-if="title=='审批'" :loading="confirmLoading" type="primary" @click="handleOk(3)">
        通过
      </a-button>
      <a-button v-if="title=='编辑'" :loading="confirmLoading" type="primary" @click="handleOk2">
        确定
      </a-button>
    </template>
    <a-divider orientation="left" style="font-weight: 600;margin-top: 0px;">基本信息</a-divider>
    <a-spin :spinning="confirmLoading">
      <a-form :form="form">
        <a-col :md="8" :sm="24">
          <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="提交人">
            <a-input v-decorator="['createName']" :disabled="disableSubmit"/>
          </a-form-item>
        </a-col>
        <a-col :md="8" :sm="24">
          <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="组织">
            <a-input v-decorator="['orgName']" :disabled="disableSubmit"/>
          </a-form-item>
        </a-col>
        <a-col :md="8" :sm="24">
          <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="下单时间">
            <a-input v-decorator="['createTime']" :disabled="disableSubmit"/>
          </a-form-item>
        </a-col>
        <a-col :md="8" :sm="24">
          <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="门店编号">
            <a-input v-decorator="['customerCode']" :disabled="disableSubmit"/>
          </a-form-item>
        </a-col>
        <a-col :md="8" :sm="24">
          <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="门店名称">
            <a-input v-decorator="['customerName']" :disabled="disableSubmit"/>
          </a-form-item>
        </a-col>
        <a-col :md="8" :sm="24">
          <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="联系电话">
            <a-input v-decorator="['consigneeTelephone']" :disabled="disableSubmit"/>
          </a-form-item>
        </a-col>
        <a-col :md="8" :sm="24">
          <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="订单类型">
            <a-input v-decorator="['orderTypeStr']" :disabled="disableSubmit"/>
          </a-form-item>
        </a-col>
        <a-col :md="8" :sm="24">
          <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="订单编号">
            <a-input v-decorator="['sfaOrderCode']" :disabled="disableSubmit"/>
          </a-form-item>
        </a-col>
        <a-col :md="8" :sm="24">
          <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="物流单号">
            <a-input v-decorator="['logisticsNo']" :disabled="disableSubmit"/>
          </a-form-item>
        </a-col>
        <a-col :md="8" :sm="24">
          <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="收货人姓名">
            <a-input v-decorator="['consignee']" :disabled="disableSubmit"/>
          </a-form-item>
        </a-col>
        <a-col :md="8" :sm="24">
          <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="收货地址">
            <a-input v-decorator="['receivingAddress']" :disabled="disableSubmit"/>
          </a-form-item>
        </a-col>
        <a-col :md="8" :sm="24">
          <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="收货人电话">
            <a-input v-decorator="['consigneeTelephone']" :disabled="disableSubmit"/>
          </a-form-item>
        </a-col>
        <a-divider orientation="left" style="font-weight: 400;margin-top: 0px;">商品信息</a-divider>

        <a-button v-if="title=='编辑'" style="margin: 10px 30px 0px 30px;" type="primary"
                  @click="handleConfigTer(record)">+商品
        </a-button>
        <div style="padding: 10px 20px;">
          <a-table ref="table" :columns="orderType == 0  ? columns : orderType == 1 ? columns2 : columns3"
                   :dataSource="dataSource2"
                   :rowSelection="{selectedRowKeys:selectedRowKeys, onChange: onSelectChange1}" :scroll="{x:400,y:240 }"
                   bordered
                   rowKey="id" size="middle"
                   @change="handleTableChange">
            <span slot="quantity" slot-scope="text,record,index">
                <a-input v-model="text" :disabled="title == '编辑' ?  false : true" style="width: 100%"
                         @change="onCellChange(record.id, 'quantity', text)"/>
            </span>
            <span slot="action" slot-scope="text, record" v-if="title=='编辑'" >
              <a :disabled="title=='审批' ? true : false" style="color: red;" @click="handleDelete2(record)">删除</a>
            </span>
          </a-table>
        </div>
        <my-shuttle-modal
          ref="orgShuttleModal"
          :columns="orgColumns"
          :columns2="orgColumns2"
          :positionCode="positionCode"
          :searchConfig="orgSearchConfig"
          keyVal="goodsCode"
          leftUrl="/goods/cnGoods/findPageList"
          title="选择商品"
          @chooseOk="chooseOk"
        ></my-shuttle-modal>
        <a-divider orientation="left" style="font-weight: 600;margin-top: 0px;">结算信息</a-divider>
        <a-col :md="12" :sm="24">
          <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="合计数量">
            <a-input v-decorator="['countQuantity']" :disabled="true"></a-input>
          </a-form-item>
        </a-col>
        <a-col :md="12" :sm="24">
          <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="合计金额">
            <a-input v-decorator="['countMoney']" :disabled="true"></a-input>
          </a-form-item>
        </a-col>
        <a-col v-if="orderType === 0 " :md="12" :sm="24">
          <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="费用承担比例">
            <a-input v-decorator="['bearingRatio']" :disabled="true"></a-input>
          </a-form-item>
        </a-col>
        <a-col v-if="orderType === 1" :md="12" :sm="24">
          <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="是否赠品">
            <a-input v-decorator="['ifGiftStr']" :disabled="true"></a-input>
          </a-form-item>
        </a-col>
        <a-col :md="12" :sm="24">
          <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="备注">
            <a-textarea v-model="remarks" :disabled="true" allow-clear placeholder="请输入备注"
                        style="width:100%;"/>
          </a-form-item>
        </a-col>
        <a-col v-if="orderType === 1" :md="12" :sm="24">
          <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="活动标题">
            <a-input v-decorator="['actName']" :disabled="true"></a-input>
          </a-form-item>
        </a-col>
        <a-col v-if="orderType === 1" :md="12" :sm="24">
          <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="活动内容">
            <a-textarea  v-decorator="['actContent']" :disabled="true" allow-clear placeholder="请输入备注"
                        style="width:100%;"/>
          </a-form-item>
        </a-col>

        <!--        <a-divider orientation='left' style='font-weight: 600;margin-top: 0px;'>审批信息</a-divider>-->
        <!--        <div>-->
        <!--          <a-steps :current="1">-->
        <!--            <a-popover slot="progressDot" slot-scope="{ index, status, prefixCls }">-->
        <!--              <template slot="content">-->
        <!--                <span>step {{ index }} status: {{ status }}</span>-->
        <!--              </template>-->
        <!--              <span :class="`${prefixCls}-icon-dot`" />-->
        <!--            </a-popover>-->
        <!--            <a-step v-for='(item,index) in data' :key='index' :description="item" :title="item" />-->
        <!--          </a-steps>-->
        <!--        </div>-->
      </a-form>
      <a-divider v-if='model.orderType == 1 && order' orientation="left" style="margin-top: 0px;display: flex;align-items: center;justify-content: center">拍照验收</a-divider>
      <a-divider v-if='model.orderType == 4 && order' orientation="left" style="margin-top: 0px;display: flex;align-items: center;justify-content: center">售后照片</a-divider>
      <div style="width: 90%;margin: 24px auto" v-if='order' >
        <viewer :images='checkImgList'>
          <a-avatar v-for="(url,uidx) in checkImgList" :key="uidx" :src="url"
                    shape="square" style="width: 100px;height: 100px;margin-right: 8px"/>
        </viewer>
      </div>
      <a-divider orientation="left" style="font-weight: 600;margin-top: 0px;">审核流程</a-divider>
      <div style="width: 90%;margin: 24px auto">
        <!--      status="error"-->
        <a-steps :current="stepsIndex" size="small">
          <a-step v-for="(item,index) in approval" :key="index"
                  :title="item.currentNodeDesc"
                  :status="item.status"
          >
            <div slot="description">
              {{ item.approvalTime }}
            </div>
            <div slot="description">
              {{ item.approvalRealName }}
            </div>
            <div slot="description" v-if="item.remarks">
              审批意见:{{item.remarks }}
            </div>
          </a-step>
        </a-steps>
      </div>
      <a-col :md="12" :sm="24">
        <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="审批意见">
          <a-textarea v-model="approvalRemarks" :disabled="title=='审批'? false : true" allow-clear placeholder="请输入审批意见"
                      style="width:100%;"/>
        </a-form-item>
      </a-col>
    </a-spin>
    <proChose ref="prochoose2" v-bind="modalProps" @okbro="okbropro2"></proChose>
  </j-modal>
</template>

<script>
import {
  httpAction,
  postAction
} from '@/api/manage'
import proChose from '@comp/cn-components/ProChose'
import pick from 'lodash.pick'
import chooseModal from '@/components/cn-components/ChooseModal'
import JTreeSelect from '@/components/cn-form/JTreeSelect'
// import WedPalnMakingMod from './WedPalnMakingMod.vue'
// import StorePlanMod from './StorePlanMod.vue'
import myShuttleModal from '@/components/cn-components/CnShuttleModal'

export default {
  name: 'SfaSignConfigModal',
  components: {
    JTreeSelect,
    chooseModal,
    proChose,
    // WedPalnMakingMod,
    // StorePlanMod,
    myShuttleModal
  },
  data() {
    return {
      name: '',
      approval: [],
      title: '操作',
      objs: [],
      value: 1,
      checkImgList:[],
      // orderType:'',
      order:false,
      positionCode: '', //职位编码
      dataSource: [],
      dataSource2: [],
      lineVos: [],
      remarks: '',
      approvalRemarks:'',
      visible: false,
      model: {},
      labelCol: {
        xs: {
          span: 24
        },
        sm: {
          span: 5
        }
      },
      wrapperCol: {
        xs: {
          span: 24
        },
        sm: {
          span: 16
        }
      },
      // 物料||售后
      columns: [
        {
          title: '商品编码',
          align: 'center',
          dataIndex: 'goodsCode'
        },
        {
          title: '商品名称',
          align: 'center',
          dataIndex: 'goodsName'
        },
        {
          title: '单位',
          align: 'center',
          dataIndex: 'basicUnitStr'
        },
        {
          title: '数量',
          align: 'center',
          dataIndex: 'quantity',
          scopedSlots: {
            customRender: 'quantity'
          }
        },
        {
          title: '单价（元）',
          align: 'center',
          dataIndex: 'unitPrice'
        },
        {
          title: '合计',
          align: 'center',
          dataIndex: 'amount'
        },
        {
          title: '操作',
          dataIndex: 'action',
          fixed: 'right',
          align: 'center',
          width: 150,
          scopedSlots: {
            customRender: 'action'
          }
        }
      ],
      //活动
      columns2: [
        {
          title: '商品编码',
          align: 'center',
          dataIndex: 'goodsCode'
        },
        {
          title: '商品名称',
          align: 'center',
          dataIndex: 'goodsName'
        },
        {
          title: '单位',
          align: 'center',
          dataIndex: 'basicUnitStr'
        },
        {
          title: '数量',
          align: 'center',
          dataIndex: 'quantity',
          scopedSlots: {
            customRender: 'quantity'
          }
        },
        {
          title: '单价（元）',
          align: 'center',
          dataIndex: 'unitPrice'
        },
        {
          title: '操作',
          dataIndex: 'action',
          fixed: 'right',
          align: 'center',
          width: 150,
          scopedSlots: {
            customRender: 'action'
          }
        }
      ],
      //周边
      columns3: [
        {
          title: '商品编码',
          align: 'center',
          dataIndex: 'goodsCode'
        },
        {
          title: '商品名称',
          align: 'center',
          dataIndex: 'goodsName'
        },
        {
          title: '单位',
          align: 'center',
          dataIndex: 'basicUnitStr'
        },
        {
          title: '数量',
          align: 'center',
          dataIndex: 'quantity',
          scopedSlots: {
            customRender: 'quantity'
          }
        },
        {
          title: '单价（元）',
          align: 'center',
          dataIndex: 'unitPrice'
        },
        {
          title: '合计',
          align: 'center',
          dataIndex: 'amount'
        },
        {
          title: '操作',
          dataIndex: 'action',
          fixed: 'right',
          align: 'center',
          width: 150,
          scopedSlots: {
            customRender: 'action'
          }
        }
      ],

      orgSearchConfig: [
        {
          type: 'input',
          placeholder: '商品编号',
          name: 'goodsCode'
        },
        {
          type: 'input',
          placeholder: '商品名称',
          name: 'goodsName'
        }
      ],
      orgColumns: [

        {
          title: '商品编号',
          align: 'center',
          dataIndex: 'goodsCode'
        },
        {
          title: '商品名称',
          align: 'center',
          dataIndex: 'goodsName'
        }
      ],
      orgColumns2: [
        {
          title: '商品编号',
          align: 'center',
          dataIndex: 'goodsCode'
        },
        {
          title: '商品名称',
          align: 'center',
          dataIndex: 'goodsName'
        },
        {
          title: '操作',
          dataIndex: 'action',
          // fixed: 'right',
          align: 'center',
          scopedSlots: {
            customRender: 'delete'
          }
        }
      ],
      /* table选中keys*/
      selectedRowKeys: [],
      /* table选中records*/
      selectionRows: [],
      selectedRowKeys2: [],
      /* table选中records*/
      selectionRows2: [],
      rule: [{
        count: 0,
        actCode: '',
        orderNum: '',
        discount: '',
        gifts: []
      }],
      chara: [],
      confirmLoading: false,
      form: this.$form.createForm(this),
      validatorRules: {
        visitDates: {
          rules: [{
            required: true,
            message: ''
          }]
        },
        visitUserRealName: {
          rules: [{
            required: true,
            message: ''
          }]
        },
        classifyName: {
          rules: [{
            required: true,
            message: ''
          }]
        },
        classifytotName: {
          rules: [{
            required: true,
            message: ''
          }]
        }
      },
      url: {
        add: window._CONFIG['domianSfaURL'] + '/visit/sfaVisitLineController/saveOrUpdate',
        savePosCust: window._CONFIG['domainURL'] + '/cnTerminalExtendController/saveTerminalExtend',
        saveUserRelation: window._CONFIG['domianURL'] + '/customerExtendController/saveExtendPos',
        addOrUpdateUrl: window._CONFIG['domianSfaURL'] + '/sfaOrderController/toExamine',
        addDetail: window._CONFIG['domianSfaURL'] + '/sfaOrderController/updateBeforeDeliverGoods'
      }
    }
  },
  computed: {
    modalProps() {
      return {
        name: this.name
      }
    },
    modalProps1() {
      return {
        name: this.name
      }
    }
  },
  methods: {
    onCellChange(key, dataIndex, value) {
      this.model.countMoney = 0
      this.model.countQuantity = 0
      console.log(key)
      // for(let i =0;i<this.dataSource.length;i++){
      //   this.dataSource[i].visitFrequency=''
      // }
      let dataSource = [...this.dataSource2]
      let target = dataSource.find(item => item.id === key)
      target[dataIndex] = value
      this.dataSource2 = dataSource
      this.model.itemVos.forEach((item, index) => {
        item.amount = 0
        item.amount = item.unitPrice * item.quantity
        this.model.countMoney += item.amount
        this.model.countQuantity += Number(item.quantity)
      })
      if(this.orderType == 0){
        this.model.countMoney=this.model.countMoney*(this.model.bearingRatio*0.01)
      }
      console.log(this.model.countMoney)
      this.dataSource2 = this.model.itemVos
      this.$nextTick(() => {
        this.form.setFieldsValue(this.model)
      })
    },
    //经销商
    onSelectChange1(selectedRowKeys, selectionRows) {
      this.selectedRowKeys = selectedRowKeys
      this.selectionRows = selectionRows
    },
    //门店新增弹窗确认
    chooseOk(e) {
      let key = this.dataSource2.map(item => {
        return item.goodsCode
      })
      console.log(e)
      let that = this
      e.forEach(item => {
        if (key.indexOf(item.goodsCode) === -1) {
          // item.goodsCode = item.goodsCode
          // item.goodsName = item.goodsName
          item.url=item.logoMobile
          item.unitPrice = item.marketingUnitMoney
          this.dataSource2.push(item)
        }
      })
    },
    okbropro2(val, status, status2) {
      let objs = JSON.parse(JSON.stringify(val[0]))
      this.objs = objs
      this.form.setFieldsValue({
        visitUserName: objs.userName,
        visitUserRealName: objs.realName,
        visitPosName: objs.positionName,
        visitPosCode: objs.positionCode,
        departName: objs.departName,
        departCode: objs.departCode
      })
      this.positionCode = this.objs.positionCode
    },
    showModal(groupCode) {
      this.visible = true
      this.reqCode = groupCode
      this.queryParam.groupCode = groupCode
    },
    //商品
    handleDelete2(e) {
      let key = this.dataSource2.map(item => {
        return item.id
      })
      this.dataSource2.splice(key.indexOf(e.id), 1)
    },
    add() {
      this.edit({})
    },
    edit(record, id) {
      console.log(this.title)
      this.form.resetFields()
      this.model = Object.assign({}, record)
      this.remarks = this.model.remarks
      this.approvalRemarks=this.model.approvalRemarks
      if (this.model.orderType == 1 ) {
        this.orderType = 0
        this.order = record.checkImgList && record.checkImgList.length?true:false
        this.checkImgList = record.checkImgList||[]
      }
      if (this.model.orderType == 2) {
        this.orderType = 1
        this.order = false
      }
      if (this.model.orderType == 3) {
        this.orderType = 2
        this.order = false
      }
      if (this.model.orderType == 4) {
        this.orderType = 4
        this.order = record.salesImgVos && record.salesImgVos.length?true:false
        this.checkImgList = record.salesImgVos||[]
      }
      this.dataSource2 = this.model.itemVos
      this.visible = true
      this.getApproval()
      this.$nextTick(() => {
        this.form.setFieldsValue(this.model)
      })
    },
    async getApproval() {
      if (this.model.id) {
        let res = await postAction(window._CONFIG['domianSfaURL'] +'/approval/sfaApprovalLog/findNodeLogList', {
          businessFlag: '订单流程',
          businessId: this.model.id
        })
        if (res.success) {
          this.approval = res.result.map((item, index) => {
            if (item.approvalStatus == 4) {
              item.status = 'error'
            } else if (item.approvalTime) {
              item.status = 'finish'
            } else if (!item.approvalTime && res.result[index - 1].approvalTime) {
              item.status = 'process'
            } else {
              item.status = 'wait'
            }
            return item
          })
        } else {
          this.$message.error(res.message)
        }
      }
    },

    handleConfigTer() {
      this.dataSource2.forEach(item => {
        this.$refs.orgShuttleModal.dataSource2.push({ goodsName: item.goodsName, goodsCode: item.goodsCode })
        this.$refs.orgShuttleModal.selectionRows.push({ goodsName: item.goodsName, goodsCode: item.goodsCode })
      })
      this.$refs.orgShuttleModal.visible = true
      this.$refs.orgShuttleModal.loadData()
    },
    close() {
      this.$emit('close')
      this.form = this.$form.createForm(this)
      this.visible = false
      this.remarks = ''
      this.approval = []
      this.dataSource = []
      this.dataSource2 = []
    },
    handleOk(status) {
      let formData = {
        approvalStatus: status,
        approvalRemarks: this.approvalRemarks,
        id: this.model.id
      }
      console.log(formData)
      this.confirmLoading = true
      let that = this
      httpAction(this.url.addOrUpdateUrl, formData, 'post').then((res) => {
        if (res.success) {
          that.$message.success(res.message)
          that.$emit('ok')
          that.close()
        } else {
          that.$message.warning(res.message)
        }
      }).finally(() => {
        that.confirmLoading = false
      })
    },
    handleOk2() {
      let formData = {
        approvalRemarks: this.remarks,
        itemVos:this.dataSource2,
        id: this.model.id
      }
      console.log(formData)
      this.confirmLoading = true
      let that = this
      httpAction(this.url.addDetail, formData, 'post').then((res) => {
        if (res.success) {
          that.$message.success(res.message)
          that.$emit('ok')
          that.close()
        } else {
          that.$message.warning(res.message)
        }
      }).finally(() => {
        that.confirmLoading = false
      })
    },
    handleCancel() {
      this.close()
    }
  }
}
</script>

<style scoped>

</style>
